#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QMessageBox>
#include <QTextCodec>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //server = new Server(1234);
   // connect(server, SIGNAL(showWindows()), this, SLOT(show_window()), Qt::QueuedConnection); // connect函数的重载，最后一个参数需要注意，不能使用默认
    QString path = QCoreApplication::applicationDirPath();
    qDebug()<<"path:"<<path;
    settings = new QSettings(path+"/config.ini", QSettings::IniFormat);
    settings->setIniCodec(QTextCodec::codecForName("UTF-8"));
    this->setWindowFlags(this->windowFlags()|Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint); //在所有窗口上置顶
    ui->centralwidget->setAttribute(Qt::WA_TranslucentBackground, true);//设置窗口背景透明
}

MainWindow::~MainWindow()
{
    delete ui;
}





void MainWindow::on_maxButton_clicked()
{
    QString wName = getDestWindowName();
    HWND hDesktop = ::FindWindow(NULL, wName.toStdWString().c_str());
//    HWND hDesktop = ::FindWindow(NULL, L"新建文本文档.txt - 记事本");
    if(::IsWindow(hDesktop)){ //句柄是否存在
        ::ShowWindow(hDesktop,SW_MAXIMIZE);
    }
}


void MainWindow::on_minButton_clicked()
{
    QString wName = getDestWindowName();
    HWND hDesktop = ::FindWindow(NULL, wName.toStdWString().c_str());
//    HWND hDesktop = ::FindWindow(NULL, L"新建文本文档.txt - 记事本");
    if(::IsWindow(hDesktop)){ //句柄是否存在
        ::ShowWindow(hDesktop,SW_MINIMIZE);
    }
}


void MainWindow::on_closeButton_clicked()
{
    on_minButton_clicked(); //最小化就足够了
//    this->hide();
}

void MainWindow::show_window(){
 this->on_maxButton_clicked();
 Sleep(300);
 if(!this->isActiveWindow()){
    qDebug() << "show_window: " ;
        this->activateWindow();
    this->show();
 }
}

void MainWindow::charTowchar(const char* str, wchar_t *wstr, int length)
{
    int len = MultiByteToWideChar(CP_ACP, 0, str, strlen(str), NULL, 0);
    MultiByteToWideChar(CP_ACP, 0, str, strlen(str), wstr, len);
    if (len < length)
        wstr[len] = '\0';
}

QString MainWindow::getDestWindowName(){
   QString wname = settings->value("window/name").toString();
   qDebug() <<wname;
   wchar_t newStr[256] = {0};
   if(wname.isEmpty()){
       QMessageBox::information(this, "目标窗口标题为空", "请检查配置文件config.ini");
       Sleep(1000);
        exit(0);
   }
   return wname;
}
